using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.Json;
using System.Windows.Forms;

namespace Toolbox.Model.Reminder
{
    /// <summary>
    /// 提醒配置管理器
    /// 专门负责提醒页签的配置读取、保存和管理，使用JSON格式
    /// </summary>
    public class ReminderConfigManager
    {
        private static ReminderConfigManager? _instance;
        private readonly string _configPath;
        private List<ReminderItem> _reminderItems;
        private readonly object _lockObject = new object();

        /// <summary>
        /// 单例实例
        /// </summary>
        public static ReminderConfigManager Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new ReminderConfigManager();
                }
                return _instance;
            }
        }

        /// <summary>
        /// 私有构造函数
        /// </summary>
        private ReminderConfigManager()
        {
            _configPath = Path.Combine(Application.StartupPath, "Conf", "ReminderConfig.json");
            _reminderItems = new List<ReminderItem>();
            
            LoadReminderItems();
        }

        /// <summary>
        /// 获取所有提醒项
        /// </summary>
        /// <returns>提醒项列表</returns>
        public List<ReminderItem> GetReminderItems()
        {
            lock (_lockObject)
            {
                return new List<ReminderItem>(_reminderItems);
            }
        }

        /// <summary>
        /// 保存所有提醒项
        /// </summary>
        /// <param name="items">提醒项列表</param>
        public void SaveReminderItems(List<ReminderItem> items)
        {
            lock (_lockObject)
            {
                _reminderItems = new List<ReminderItem>(items);
                SaveAllReminderItems();
            }
        }

        /// <summary>
        /// 获取指定ID的提醒项
        /// </summary>
        /// <param name="id">提醒项ID</param>
        /// <returns>提醒项，如果不存在则返回null</returns>
        public ReminderItem? GetReminderItem(string id)
        {
            lock (_lockObject)
            {
                return _reminderItems.Find(item => item.Id == id);
            }
        }

        /// <summary>
        /// 更新指定ID的提醒项
        /// </summary>
        /// <param name="item">要更新的提醒项</param>
        public void UpdateReminderItem(ReminderItem item)
        {
            lock (_lockObject)
            {
                int index = _reminderItems.FindIndex(existingItem => existingItem.Id == item.Id);
                if (index >= 0)
                {
                    _reminderItems[index] = item;
                    SaveAllReminderItems();
                }
            }
        }

        /// <summary>
        /// 加载所有提醒项
        /// </summary>
        private void LoadReminderItems()
        {
            try
            {
                if (File.Exists(_configPath))
                {
                    string json = File.ReadAllText(_configPath);
                    var options = new JsonSerializerOptions
                    {
                        PropertyNameCaseInsensitive = true,
                        WriteIndented = true,
                        Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping // 保留中文字符，不进行Unicode转义
                    };
                    
                    var config = JsonSerializer.Deserialize<ReminderConfig>(json, options);
                    if (config?.ReminderItems != null)
                    {
                        _reminderItems = config.ReminderItems;
                        return;
                    }
                }
                
                // 如果没有配置文件或配置无效，创建默认提醒项
                CreateDefaultReminders();
            }
            catch (Exception)
            {
                // 配置文件读取失败，创建默认提醒项
                CreateDefaultReminders();
            }
        }

        /// <summary>
        /// 保存所有提醒项到文件
        /// </summary>
        private void SaveAllReminderItems()
        {
            try
            {
                // 确保配置文件所在的目录存在
                string? configDir = Path.GetDirectoryName(_configPath);
                if (!string.IsNullOrEmpty(configDir) && !Directory.Exists(configDir))
                {
                    Directory.CreateDirectory(configDir);
                }
                
                var config = new ReminderConfig
                {
                    ReminderItems = _reminderItems,
                    LastUpdated = DateTime.Now
                };
                
                var options = new JsonSerializerOptions
                {
                    PropertyNameCaseInsensitive = true,
                    WriteIndented = true,
                    Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping // 保留中文字符，不进行Unicode转义
                };
                
                string json = JsonSerializer.Serialize(config, options);
                File.WriteAllText(_configPath, json);
            }
            catch (Exception)
            {
                // 保存失败忽略
            }
        }

        /// <summary>
        /// 创建默认提醒项
        /// </summary>
        private void CreateDefaultReminders()
        {
            _reminderItems.Clear();
            
            // 久坐提醒
            _reminderItems.Add(new ReminderItem
            {
                Id = "sitting",
                Name = "久坐提醒",
                Interval = 45,
                Message = "您已经坐了很长时间了！建议站起来活动一下，看看远处",
                IsEnabled = false,
                NextReminderTime = DateTime.Now.AddMinutes(45)
            });
            
            // 喝水提醒
            _reminderItems.Add(new ReminderItem
            {
                Id = "water",
                Name = "喝水提醒",
                Interval = 60,
                Message = "该喝水了！保持充足的水分摄入对健康很重要",
                IsEnabled = false,
                NextReminderTime = DateTime.Now.AddMinutes(60)
            });
            
            // 保存默认设置
            SaveAllReminderItems();
        }
    }

    /// <summary>
    /// 提醒配置数据结构
    /// </summary>
    public class ReminderConfig
    {
        public List<ReminderItem> ReminderItems { get; set; } = new List<ReminderItem>();
        public DateTime LastUpdated { get; set; } = DateTime.Now;
    }
}